using UnityEngine;
using UnityEngine.UI;
using GameSystems;

namespace Examples
{
    /// <summary>
    /// 登录系统使用示例 - 展示如何正确使用GameLoginSystem
    /// </summary>
    public class LoginSystemExample : MonoBehaviour
    {
        #region Serialized Fields

        [Header("组件引用")]
        [Tooltip("登录系统组件")]
        [SerializeField] private GameLoginSystem loginSystem;

        [Tooltip("用户数据管理器")]
        [SerializeField] private UserDataManager userDataManager;

        [Header("UI元素")]
        [Tooltip("主菜单面板")]
        [SerializeField] private GameObject mainMenuPanel;

        [Tooltip("登录面板")]
        [SerializeField] private GameObject loginPanel;

        [Tooltip("用户信息文本")]
        [SerializeField] private Text userInfoText;

        [Tooltip("登录状态文本")]
        [SerializeField] private Text loginStatusText;

        #endregion

        #region Unity Lifecycle

        /// <summary>
        /// 初始化组件
        /// </summary>
        private void Start()
        {
            InitializeLoginSystem();
        }

        /// <summary>
        /// 清理资源
        /// </summary>
        private void OnDestroy()
        {
            CleanupLoginSystem();
        }

        #endregion

        #region Initialization

        /// <summary>
        /// 初始化登录系统
        /// </summary>
        private void InitializeLoginSystem()
        {
            if (loginSystem == null)
            {
                loginSystem = FindObjectOfType<GameLoginSystem>();
            }

            if (userDataManager == null)
            {
                userDataManager = ScriptableObject.CreateInstance<UserDataManager>();
            }

            if (loginSystem != null)
            {
                // 订阅登录事件
                loginSystem.OnLoginSuccess.AddListener(OnLoginSuccess);
                loginSystem.OnLoginFailed.AddListener(OnLoginFailed);
                loginSystem.OnLoginStateChanged.AddListener(OnLoginStateChanged);

                Debug.Log("登录系统事件已注册");
            }
            else
            {
                Debug.LogError("未找到GameLoginSystem组件");
            }
        }

        /// <summary>
        /// 清理登录系统
        /// </summary>
        private void CleanupLoginSystem()
        {
            if (loginSystem != null)
            {
                // 取消订阅事件
                loginSystem.OnLoginSuccess.RemoveListener(OnLoginSuccess);
                loginSystem.OnLoginFailed.RemoveListener(OnLoginFailed);
                loginSystem.OnLoginStateChanged.RemoveListener(OnLoginStateChanged);
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// 登录成功事件处理
        /// </summary>
        /// <param name="username">用户名</param>
        private void OnLoginSuccess(string username)
        {
            Debug.Log($"登录成功: {username}");

            // 初始化用户数据
            if (userDataManager != null)
            {
                userDataManager.InitializeUser(username);

                // 更新用户信息显示
                UpdateUserInfoDisplay();
            }

            // 显示主菜单，隐藏登录面板
            if (mainMenuPanel != null)
            {
                mainMenuPanel.SetActive(true);
            }

            if (loginPanel != null)
            {
                loginPanel.SetActive(false);
            }

            // 更新登录状态
            UpdateLoginStatus($"已登录: {username}");
        }

        /// <summary>
        /// 登录失败事件处理
        /// </summary>
        /// <param name="errorMessage">错误信息</param>
        private void OnLoginFailed(string errorMessage)
        {
            Debug.LogError($"登录失败: {errorMessage}");

            // 显示错误信息
            UpdateLoginStatus($"登录失败: {errorMessage}");

            // 可以在这里添加更多的错误处理逻辑
            // 例如：震动反馈、错误音效等
        }

        /// <summary>
        /// 登录状态改变事件处理
        /// </summary>
        /// <param name="isLoggedIn">是否已登录</param>
        private void OnLoginStateChanged(bool isLoggedIn)
        {
            Debug.Log($"登录状态改变: {isLoggedIn}");

            if (isLoggedIn)
            {
                UpdateLoginStatus("登录成功");
            }
            else
            {
                UpdateLoginStatus("未登录");

                // 显示登录面板，隐藏主菜单
                if (loginPanel != null)
                {
                    loginPanel.SetActive(true);
                }

                if (mainMenuPanel != null)
                {
                    mainMenuPanel.SetActive(false);
                }
            }
        }

        #endregion

        #region UI Updates

        /// <summary>
        /// 更新用户信息显示
        /// </summary>
        private void UpdateUserInfoDisplay()
        {
            if (userDataManager == null || userInfoText == null) return;

            UserDataManager.UserData userData = userDataManager.CurrentUserData;
            if (userData != null)
            {
                string info = $"用户名: {userData.username}\n";
                info += $"登录次数: {userData.loginCount}\n";
                info += $"游戏时间: {FormatPlayTime(userData.totalPlayTime)}\n";
                info += $"最后登录: {userData.lastLoginDate:yyyy-MM-dd HH:mm}";

                userInfoText.text = info;
            }
        }

        /// <summary>
        /// 更新登录状态显示
        /// </summary>
        /// <param name="status">状态文本</param>
        private void UpdateLoginStatus(string status)
        {
            if (loginStatusText != null)
            {
                loginStatusText.text = status;
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// 手动注销
        /// </summary>
        public void Logout()
        {
            if (loginSystem != null)
            {
                loginSystem.Logout();
            }
        }

        /// <summary>
        /// 保存用户数据
        /// </summary>
        public void SaveUserData()
        {
            if (userDataManager != null)
            {
                userDataManager.SaveUserData();
                Debug.Log("用户数据已保存");
            }
        }

        /// <summary>
        /// 更新游戏时间（示例）
        /// </summary>
        public void UpdatePlayTime()
        {
            if (userDataManager != null)
            {
                userDataManager.AddPlayTime(60); // 增加60秒
                UpdateUserInfoDisplay();
            }
        }

        /// <summary>
        /// 设置用户等级（示例）
        /// </summary>
        /// <param name="level">等级</param>
        public void SetUserLevel(int level)
        {
            if (userDataManager != null)
            {
                userDataManager.UpdateCustomData("level", level);
                userDataManager.UpdateCustomData("lastLevelUp", System.DateTime.Now.ToString());
                UpdateUserInfoDisplay();
            }
        }

        #endregion

        #region Utility Methods

        /// <summary>
        /// 格式化游戏时间显示
        /// </summary>
        /// <param name="seconds">秒数</param>
        /// <returns>格式化的时间字符串</returns>
        private string FormatPlayTime(int seconds)
        {
            int hours = seconds / 3600;
            int minutes = (seconds % 3600) / 60;
            int secs = seconds % 60;

            if (hours > 0)
            {
                return $"{hours}小时{minutes}分钟{secs}秒";
            }
            else if (minutes > 0)
            {
                return $"{minutes}分钟{secs}秒";
            }
            else
            {
                return $"{secs}秒";
            }
        }

        #endregion

        #region Context Menu Methods

        /// <summary>
        /// 测试登录功能（仅在编辑器中可用）
        /// </summary>
        [ContextMenu("测试登录")]
        private void TestLogin()
        {
            if (loginSystem != null)
            {
                loginSystem.LoginWithTestAccount();
            }
        }

        /// <summary>
        /// 测试注销功能（仅在编辑器中可用）
        /// </summary>
        [ContextMenu("测试注销")]
        private void TestLogout()
        {
            Logout();
        }

        /// <summary>
        /// 强制保存数据（仅在编辑器中可用）
        /// </summary>
        [ContextMenu("强制保存数据")]
        private void ForceSaveData()
        {
            SaveUserData();
        }

        #endregion
    }
}
